package com.youdianstar.app.ui.reward

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.youdianstar.app.R
import com.youdianstar.app.BR

import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.base.BaseFragment
import com.youdianstar.app.entity.CouponInfo
import com.youdianstar.app.common.network.BaseApiPagingObserver
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.widget.adapter.FooterAdapter

import com.youdianstar.app.adapter.RedeemPagingAdapter
import com.youdianstar.app.databinding.FragmentRedeemListBinding
import com.youdianstar.app.entity.PointAccount
import com.youdianstar.app.support.imp.IItemSelectListener
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.util.WalletDialogUtil
import kotlinx.coroutines.flow.collectLatest
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: RedeemFragment
 * Author: 82149 Create: 2022/2/28 17:25
 * Changes (from 2022/2/28)
 * --------------------------------------------------
 * description: 兑换列表(优惠券中心 改)
 * ---------------------------------------------------
 *
 */
class RedeemFragment : BaseFragment<FragmentRedeemListBinding, RewardViewModel>() {

    override fun initContentView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): Int {
        return R.layout.fragment_redeem_list
    }

    override fun initVariableId(): Int = BR.fragModel

    override fun initViewModel(): RewardViewModel {
        val model: RewardViewModel by viewModel()
        return model
    }

    companion object {
        fun newInstance(type: Int, titleTag: String,pointBalance:Int): RedeemFragment {
            val bundle = Bundle()
            bundle.putInt(Extra.IT_TYPE, type)
            bundle.putString("Tag", titleTag)
            bundle.putInt("balance", pointBalance)
            val fragment = RedeemFragment()
            fragment.arguments = bundle
            return fragment
        }
    }

    // 0-通用优惠券 1-商家优惠券
    private var dataType = 0
    private var mPagingAdapter: RedeemPagingAdapter? = null

    private var redeemPointDialog: Dialog? = null
    private val mHandler = Handler(Looper.myLooper()!!)

    override fun initData() {
        val type = arguments?.getInt(Extra.IT_TYPE)
        val tag = arguments?.getString("Tag")
        val balance = arguments?.getInt("balance")?:0
        dataType = type?:0

        mPagingAdapter = RedeemPagingAdapter(activity?.baseContext!!,dataType,object : IItemSelectListener {
            override fun onSelectItem(position: Int, type: Int, info: CouponInfo) {
                pointRedeemSheet(info)
            }
        })
        mPagingAdapter?.setPointBalance(balance)

        binding.run {
            rcList.adapter = mPagingAdapter?.withLoadStateFooter(FooterAdapter {
                //重新请求
                mPagingAdapter?.retry()
            })
            //刷新监听
            swRedeem.setOnRefreshListener {
                mPagingAdapter?.refresh()
            }
            lifecycleScope.launchWhenCreated {
                mPagingAdapter?.loadStateFlow?.collectLatest {
                    swRedeem.isRefreshing = it.refresh is LoadState.Loading
                }
            }

            loadListData(dataType)
        }
    }

    override fun initClickEvent() {

    }

    override fun initLiveObserver() {
        viewModel.redeemPagingLiveData.observe(this, object : BaseApiPagingObserver(binding.rcList){
            override fun onReload(v: View?) {
                loadListData(dataType)
            }
        })

        viewModel.redeemPointResultData.observe(this,object : BaseApiResultObserver<Any>(true){
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                //兑换积分结果
                dismissDialog()
                toastShow(getString(R.string.public_success))
                DataAppManager.instance.couponUpdateTag = true
                mHandler.postDelayed({
                    viewModel.getPointAccount(isShow = true)
                },500L)
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        viewModel.pointAccountLiveData.observe(this,object : BaseApiResultObserver<PointAccount>(){
            override fun onDataResult(data: PointAccount?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    DataAppManager.instance.pointBalance = it.point
                    mPagingAdapter?.setPointBalance(it.point) //更新积分数据
                    mPagingAdapter?.notifyDataSetChanged()
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })
    }

    /**
     * 获取数据
     * @param type 0-通用优惠券 1-商家优惠券
     */
    private fun loadListData(type :Int){
        lifecycleScope.launchWhenCreated {
            viewModel.getRedeemCouponsPaging(type).collectLatest {
                //要测试这里是否能 获取到数据结果
                mPagingAdapter?.submitData(it)
            }
        }
    }


    /**
     * 优惠券兑换
     * --积分兑换优惠券提示
     *
     * @param info 兑换优惠券数据
     */
    private fun pointRedeemSheet(info : CouponInfo){
        if(redeemPointDialog!=null){
            redeemPointDialog?.dismiss()
            redeemPointDialog = null
        }
        redeemPointDialog = WalletDialogUtil.instance.sheetRedeemPoints(requireActivity(),
            DataAppManager.instance.pointBalance,info,redeemAction = {
            //调用 接口
            viewModel.redeemCouponWithPoints(info.id)
        })
    }

}